package com.brother.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.brother.*;
import com.brother.model.Customer;


public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req1, ServletResponse res1,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) req1;
		HttpServletResponse res = (HttpServletResponse) res1;
		req.setCharacterEncoding("UTF-8");
		String url = req.getRequestURI();
		HttpSession session = req.getSession();
		Customer c = (Customer) session.getAttribute(Constants.LOGIN_SESSTION_NAME);
		//if(this.hasUrl(url)){
		
			if(c == null && url.indexOf("login.jsp") ==-1 && (url.endsWith("jsp") || url.length() == 0 || url.endsWith("/"))){
				String contextPath = req.getContextPath() + "/";
				contextPath = contextPath.replace("//", "/");
				res.sendRedirect(contextPath + "login.jsp?redirectUrl="+url);
			}
		//}
		
		if(url.indexOf("admin") > -1 && (url.indexOf("login.jsp") ==-1)){
			if(c == null || c.isAdmin() == false){
				res.sendRedirect("login.jsp");
			}
		}
		
		chain.doFilter(req, res);
	}
	private boolean chekLogin(HttpServletRequest req) {
		HttpSession session = req.getSession();
		if(session.getAttribute(Constants.LOGIN_SESSTION_NAME) != null)
			return true;
		return false;
	}

	private boolean hasUrl(String url) {
		for(String s: this.loginPages){
			if(url.indexOf(s) > -1){
				return true;
			}
		}
		return false;
	}
	private String[] loginPages = null;
	@Override
	public void init(FilterConfig con) throws ServletException {
		String param = con.getInitParameter("loginPages");
		if(param != null){
			loginPages = param.split(",");
		}
	}

}
